
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class xmlReader {
	public static Polynomial xmlToPolynom(String filepath){
		try {

			// Creating file object
			File file = new File(filepath);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();

			//parsing file

			Element ele = doc.getDocumentElement();
			String functionID = ele.getAttribute("id");
			//System.out.println("Root element " + functionID);


			Polynomial result = new Polynomial(); //will be returned.


			NodeList nodeLst = ele.getElementsByTagName("function");

			for (int s = 0; s < nodeLst.getLength(); s++) { //go over functions

				// Getting the current node
				Node currNode = nodeLst.item(s);

				Element funcElem = (Element) currNode;
				if(funcElem.getAttribute("id").equalsIgnoreCase(functionID)){
					NodeList monomLst = funcElem.getElementsByTagName("monom");

					double[] realParts = new double[monomLst.getLength()];
					double[] imParts = new double[monomLst.getLength()];
					int[] alphaParts = new int[monomLst.getLength()];
					for(int i=0;i<monomLst.getLength();i++){ 
					NodeList reals = funcElem.getElementsByTagName("real");
					realParts[i] = new Double(reals.item(i).getTextContent());
					NodeList ims = funcElem.getElementsByTagName("image");
					imParts[i] = new Double(ims.item(i).getTextContent());
					NodeList alphas = funcElem.getElementsByTagName("alpha");
					alphaParts[i] = new Integer(alphas.item(i).getTextContent());

					result.addMonomial(alphaParts[i],new Complex(realParts[i],imParts[i]));
					
				}
			}
		}
		return result;

	}catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
}

